package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.example.entity.Email;
import org.example.entity.Session;
import org.example.entity.User;
import org.example.service.IEmailService;
import org.example.service.ISessionService;
import org.example.service.IUserService;
import org.example.util1.WebFaceCompare;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.MessageFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-06-13
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    JavaMailSenderImpl mailSender;
    @Value("${spring.mail.username}")
    private String myEmail;
    @Value("${upload.path}")
    private String uploadPath;
    @Autowired
    IUserService userService;
    @Autowired
    IEmailService emailService;
    @Autowired
    ISessionService sessionService;

    @PostMapping("/reg")
    public Map<String, String> reg(@RequestBody Map<String, String> req) {
        Map<String, String> map = new HashMap<>();
        System.out.println("------req--reg->" + req);
//        判断验证码是否正确
        QueryWrapper<Email> qw1 = new QueryWrapper<Email>();
        qw1.eq("email",req.get("account"));
        qw1.eq("code",req.get("code"));
        Email email = emailService.getOne(qw1);
        if(email==null){
            System.out.println("验证码错误");
            map.put("errorMsg", "验证码错误");
            return map;
        }
//        判断用户是否存在
        User user = new User();
        user.setAccount(req.get("account"));
        user.setPwd(req.get("pwd"));
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("account", req.get("account"));
        User user1 = userService.getOne(qw);
        if (user1 == null) {
            boolean res = userService.save(user);
            if (res) {
                System.out.println("注册成功");
                map.put("success", "注册成功");
                return map;
            } else {
                System.out.println("注册失败");
                map.put("errorMsg", "注册失败");
                return map;
            }
        } else {
            System.out.println("用户已存在");
            map.put("errorMsg", "用户已存在");
            return map;
        }

    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> req) {
        Map<String, Object> map = new HashMap<>();
        System.out.println("------req-login-->" + req);
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("account", req.get("account"));
        qw.eq("pwd", req.get("pwd"));
        User user = userService.getOne(qw);
        System.out.println(user);
        if (user == null) {
            map.put("errorMsg","用户不存在");
            return map;
        }
        Session session = new Session();
        session.setKey1(user.getId().toString());
        sessionService.save(session);
        map.put("success",user);
        return map;
    }

    @PostMapping("/update")
    public Map<String, String> update(@RequestBody Map<String, String> req) {
        System.out.println("------req-login-->" + req);
        User user = new User();
        user.setId(Integer.valueOf(req.get("id")));
        user.setLogo(req.get("logo"));
        boolean res = userService.updateById(user);
        Map<String, String> map = new HashMap<>();
        if (res) {
            map.put("success", "true");
            return map;
        }
        map.put("errorMsg", "修改失败");
        return map;
    }

    @PostMapping("/registCode")
    @ApiOperation("获取注册验证码")
    public Map<String, String> registCode(@RequestBody Map<String, String> req) {
        Map<String, String> map = new HashMap<>();
        //通过邮箱查询数据库是否已注册
        //Menber menber = new Menber();
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("account", req.get("email"));
        User menber1 = userService.getOne(qw);
        if (menber1 != null) {
            map.put("errorMsg", "该邮箱已注册");
            return map;//该邮箱已注册
        } else {
            Random r = new Random();
            String code = r.nextInt(899999) + 100000 + "";
            System.out.println("==========================code=验证码=============================="+code);
            Email email1 = new Email();
            email1.setEmail(req.get("email"));
            email1.setCode(code);
            boolean res = emailService.save(email1);
            if (res) {
                boolean ret = sendEmail(code, req.get("email"), "templates/regCode.html");
                if (ret) {
                    map.put("success", "发送成功");
                    return map;
                } else {
                    map.put("errorMsg", "发送失败");
                    return map;
                }
            } else {
                map.put("errorMsg", "请重新获取");
                return map;
            }
        }
    }
    /**
     * 发送邮件的方法
     *
     * @param code    验证码
     * @param toEmail 收件箱
     */
    public boolean sendLoginEmail(String code, String toEmail, String html) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //获取验证码 存入redis
            //int randomCode = (int) ((Math.random() * 9 + 1) * 100000);
            //redisUtil.set(Constant.CUSTOMER_EMAIL + email, randomCode, 1800);
            //邮箱发送内容组成
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject("验证码"); /// 标题
            helper.setText(buildContent(code, html), true);
            helper.setTo(toEmail);
            helper.setFrom(myEmail);
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //throw new CustomerException(messageSourceUtil.getMessage(I18nConstant.SYSTEM_ERROR), "500");
            return false;
        }
    }

    /**
     * 发送邮件的方法
     *
     * @param code    注册验证码
     * @param toEmail 收件箱
     */
    public boolean sendEmail(String code, String toEmail, String html) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            Email email = new Email();
            email.setCode(code);
            email.setEmail(toEmail);
            //int randomCode = (int) ((Math.random() * 9 + 1) * 100000);
            //redisUtil.set(Constant.CUSTOMER_EMAIL + email, randomCode, 1800);
            //邮箱发送内容组成
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject("验证码"); /// 标题
            helper.setText(buildContent(code, html), true);
            helper.setTo(toEmail);
            helper.setFrom(myEmail);
            mailSender.send(message);
            return true;
        } catch (
                Exception e) {
            e.printStackTrace();
            //throw new CustomerException(messageSourceUtil.getMessage(I18nConstant.SYSTEM_ERROR), "500");
            return false;
        }

    }


    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @param title 内容
     * @return
     */
    public String buildContent(String title, String htmlPath) {
        //加载邮件html模板
        Resource resource = new ClassPathResource(htmlPath);
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // log.info("发送邮件读取模板失败{}", e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), title);
    }

    @PostMapping("/testFace")
    @ApiOperation("人脸识别")
    public String testFace(@RequestBody Map<String, String> req) throws Exception {
        WebFaceCompare demo = new WebFaceCompare();
        WebFaceCompare.ResponseData respData = demo.faceContrast(req.get("path1"), req.get("path2"));
        if (respData != null && respData.getPayLoad().getFaceCompareResult() != null) {
            String textBase64 = respData.getPayLoad().getFaceCompareResult().getText();
            String text = new String(Base64.getDecoder().decode(textBase64));
            System.out.println("人脸比对结果(text)base64解码后：");
            System.out.println(text);
            return text;
        }
        return "over";
    }

    @PostMapping("/upload")
    public Map<String, String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        System.out.println("fileName=====>");
        if (file.isEmpty()) {
            map.put("errorMsg", "文件为空，请选择一个文件上传");
            return map;
        }
        String fileName = file.getOriginalFilename();
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("=====>path" + path);
        path = path.substring(0, path.indexOf("/java_demo"));
        String filePath = path + "/java_demo/upload/" + System.currentTimeMillis() + fileName;

        File dest = new File(filePath);
        System.out.println("fileName=====>" + fileName);
        try {
            file.transferTo(dest);
            System.out.println("文件上传成功=====>" + filePath);
            map.put("success", filePath);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文件上传失败=====>");
        map.put("errorMsg", "文件上传失败");
        return map;
    }

    @PostMapping("/faceLogin")
    public String faceLogin(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
        System.out.println("fileName=====>");
        if (file.isEmpty()) {
            map.put("errorMsg", "文件为空，请选择一个文件上传");
            return "文件为空，请选择一个文件上传";
        }
        String fileName = file.getOriginalFilename();
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("=====>path" + path);
        path = path.substring(0, path.indexOf("/java_demo"));
        String filePath = path + "/java_demo/upload/" + System.currentTimeMillis() + fileName;

        File dest = new File(filePath);
        System.out.println("fileName=====>" + fileName);
        try {
            file.transferTo(dest);
            System.out.println("文件上传成功=====>" + filePath);
            QueryWrapper<User> qw = new QueryWrapper<User>();
            qw.eq("id", request.getHeader("token"));
            User user = userService.getOne(qw);
            WebFaceCompare demo = new WebFaceCompare();
            WebFaceCompare.ResponseData respData = demo.faceContrast(user.getLogo(), filePath);
            if (respData != null && respData.getPayLoad().getFaceCompareResult() != null) {
                String textBase64 = respData.getPayLoad().getFaceCompareResult().getText();
                String text = new String(Base64.getDecoder().decode(textBase64));
                System.out.println("人脸比对结果(text)base64解码后：");
                System.out.println(text);
                return text;
            }
            return "对比失败";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }
    @PostMapping("/updateLogo")
    public String updateLogo(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
        System.out.println("fileName=====>");
        if (file.isEmpty()) {
            map.put("errorMsg", "文件为空，请选择一个文件上传");
            return "文件为空，请选择一个文件上传";
        }
        String fileName = file.getOriginalFilename();
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.println("=====>path" + path);
        path = path.substring(0, path.indexOf("/java_demo"));
        String filePath = path + "/java_demo/upload/" + System.currentTimeMillis() + fileName;
        File dest = new File(filePath);
        System.out.println("fileName=====>" + fileName);
        try {
            file.transferTo(dest);
            System.out.println("文件上传成功=====>" + filePath);
            User qw = new User();
            qw.setId(Integer.valueOf(request.getHeader("token")));
            qw.setLogo(filePath);
            boolean res = userService.updateById(qw);
            if(res){
                return "修改成功";
            }
            return "修改失败";
        } catch (IOException e) {
            e.printStackTrace();
            return "修改失败了";
        }
    }
    @PostMapping("/getUserInfo")
    public Map<String, Object> getUserInfo(@RequestBody Map<String, Object> req) {
        Map<String, Object> map = new HashMap<>();
        User user = userService.getById((Serializable) req.get("id"));
        System.out.println("==============user============"+user);
        if(user!=null){
            map.put("success", user);
            return map;
        }
        map.put("errorMsg", "用户不存在");
        return map;
    }
}
